<template>
  <div class="tenant-switcher" v-if="availableTenants.length > 1">
    <div class="switcher-header">
      <h3 class="switcher-title">
        <icon-apps />
        租户切换
      </h3>
      <a-tooltip content="刷新租户列表">
        <a-button type="text" size="small" :loading="loading" @click="refreshTenants">
          <template #icon>
            <icon-refresh />
          </template>
        </a-button>
      </a-tooltip>
    </div>

    <div class="current-tenant">
      <div class="tenant-info">
        <div class="tenant-avatar">
          <a-avatar :size="40" class="tenant-avatar-inner">
            {{ currentTenant?.name?.charAt(0) || 'T' }}
          </a-avatar>
        </div>
        <div class="tenant-details">
          <div class="tenant-name">{{ currentTenant?.name || '未选择租户' }}</div>
          <div class="tenant-status" :class="getStatusClass(currentTenant?.status)">
            <a-tag :color="getStatusColor(currentTenant?.status)" size="small">
              {{ getStatusText(currentTenant?.status) }}
            </a-tag>
          </div>
        </div>
      </div>
    </div>

    <div class="tenant-list">
      <div class="list-header">
        <span class="list-title">可切换租户 ({{ availableTenants.length }})</span>
      </div>

      <div class="tenant-items">
        <div
          v-for="tenant in availableTenants"
          :key="tenant.id"
          class="tenant-item"
          :class="{
            'tenant-item--active': tenant.id === currentTenant?.id,
            'tenant-item--inactive': tenant.status !== 'active'
          }"
          @click="handleTenantSwitch(tenant)"
        >
          <div class="item-avatar">
            <a-avatar :size="32">
              {{ tenant.name.charAt(0) }}
            </a-avatar>
          </div>

          <div class="item-content">
            <div class="item-name">
              {{ tenant.name }}
              <icon-check-circle-fill v-if="tenant.id === currentTenant?.id" class="active-icon" />
            </div>
            <div class="item-desc" v-if="tenant.description">
              {{ tenant.description }}
            </div>
          </div>

          <div class="item-status">
            <a-tag :color="getStatusColor(tenant.status)" size="small">
              {{ getStatusText(tenant.status) }}
            </a-tag>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { Message } from '@arco-design/web-vue';
import { IconApps, IconRefresh, IconCheckCircleFill } from '@arco-design/web-vue/es/icon';
import { computed } from 'vue';

import type { TenantInfo } from '@/api/auth';
import { useUserStore } from '@/stores';

interface Emits {
  (e: 'switch', tenant: TenantInfo): void;
  (e: 'refresh'): void;
}

const emit = defineEmits<Emits>();

const userStore = useUserStore();

// 计算属性
const currentTenant = computed(() => userStore.currentTenant);
const availableTenants = computed(() => userStore.availableTenants);
const loading = computed(() => userStore.isLoading);

// 获取状态颜色
const getStatusColor = (status?: string) => {
  const colorMap: Record<string, string> = {
    active: 'green',
    inactive: 'gray',
    suspended: 'red',
    pending: 'orange'
  };
  return colorMap[status || 'inactive'] || 'gray';
};

// 获取状态文本
const getStatusText = (status?: string) => {
  const textMap: Record<string, string> = {
    active: '正常',
    inactive: '未激活',
    suspended: '已暂停',
    pending: '待审核'
  };
  return textMap[status || 'inactive'] || '未知';
};

// 获取状态样式类
const getStatusClass = (status?: string) => {
  return `status-${status || 'inactive'}`;
};

// 处理租户切换
const handleTenantSwitch = async (tenant: TenantInfo) => {
  if (tenant.id === currentTenant.value?.id) {
    return;
  }

  if (tenant.status !== 'active') {
    Message.warning('该租户当前不可用，无法切换');
    return;
  }

  try {
    await userStore.switchTenant(tenant.id);
    emit('switch', tenant);
  } catch (error) {
    console.error('切换租户失败:', error);
  }
};

// 刷新租户列表
const refreshTenants = async () => {
  try {
    await userStore.fetchAvailableTenants();
    emit('refresh');
    Message.success('租户列表已更新');
  } catch (error) {
    console.error('刷新租户列表失败:', error);
    Message.error('刷新失败，请稍后重试');
  }
};
</script>

<style scoped lang="less">
.tenant-switcher {
  background: var(--color-bg-1);
  border: 1px solid var(--color-border-1);
  border-radius: 12px;
  overflow: hidden;
}

.switcher-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid var(--color-border-1);
  background: var(--color-fill-1);
}

.switcher-title {
  margin: 0;
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
  color: var(--color-text-1);

  .arco-icon {
    font-size: 18px;
    color: rgb(var(--primary-6));
  }
}

.current-tenant {
  padding: 20px;
  border-bottom: 1px solid var(--color-border-1);
}

.tenant-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.tenant-avatar {
  .tenant-avatar-inner {
    background: rgb(var(--primary-6));
    color: white;
    font-weight: 600;
  }
}

.tenant-details {
  flex: 1;
}

.tenant-name {
  font-size: 16px;
  font-weight: 600;
  color: var(--color-text-1);
  margin-bottom: 4px;
}

.tenant-status {
  display: flex;
  align-items: center;
}

.tenant-list {
  padding: 16px 0;
}

.list-header {
  padding: 0 20px 12px;
  border-bottom: 1px solid var(--color-border-2);
}

.list-title {
  font-size: 14px;
  font-weight: 500;
  color: var(--color-text-2);
}

.tenant-items {
  max-height: 300px;
  overflow-y: auto;
}

.tenant-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 20px;
  cursor: pointer;
  transition: all 0.2s ease;

  &:hover {
    background: var(--color-fill-1);
  }

  &--active {
    background: rgb(var(--primary-1));

    &:hover {
      background: rgb(var(--primary-2));
    }
  }

  &--inactive {
    opacity: 0.6;
    cursor: not-allowed;

    &:hover {
      background: transparent;
    }
  }
}

.item-avatar {
  .arco-avatar {
    background: var(--color-fill-3);
    color: var(--color-text-2);
    font-weight: 500;
  }

  .tenant-item--active & .arco-avatar {
    background: rgb(var(--primary-6));
    color: white;
  }
}

.item-content {
  flex: 1;
  min-width: 0;
}

.item-name {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 14px;
  font-weight: 500;
  color: var(--color-text-1);
  margin-bottom: 2px;
}

.active-icon {
  color: rgb(var(--success-6));
  font-size: 16px;
}

.item-desc {
  font-size: 12px;
  color: var(--color-text-3);
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.item-status {
  flex-shrink: 0;
}

// 滚动条样式
.tenant-items {
  &::-webkit-scrollbar {
    width: 4px;
  }

  &::-webkit-scrollbar-track {
    background: var(--color-fill-2);
  }

  &::-webkit-scrollbar-thumb {
    background: var(--color-fill-4);
    border-radius: 2px;

    &:hover {
      background: var(--color-fill-3);
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .tenant-switcher {
    margin: 0 -16px;
    border-radius: 0;
    border-left: none;
    border-right: none;
  }

  .switcher-header,
  .current-tenant,
  .list-header,
  .tenant-item {
    padding-left: 16px;
    padding-right: 16px;
  }
}
</style>
